package com.eagle.scali.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.OrderedGatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractNameValueGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

/**
 * PreLog需要和配置文件一致
 * 需要GatewayFilterFactory结尾
 */
@Slf4j
@Component
public class PreLogGatewayFilterFactory
    extends AbstractNameValueGatewayFilterFactory {
    @Override
    public GatewayFilter apply(NameValueConfig config) {
		GatewayFilter filter =  ((exchange, chain) -> {
			//获取到配置文件中的key,value
			log.info("请求进来了...{},{}", config.getName(), config.getValue());
			//修改后的request
			ServerHttpRequest modifiedRequest = exchange.getRequest()
					.mutate()
					.build();
			//将修改后的request放入exchange
			ServerWebExchange modifiedExchange = exchange.mutate()
					.request(modifiedRequest)
					.build();
			//传给下一个过滤器
			return chain.filter(modifiedExchange);
		});
		return new OrderedGatewayFilter(filter, 3);

//        return ((exchange, chain) -> {
//        	//获取到配置文件中的key,value
//            log.info("请求进来了...{},{}", config.getName(), config.getValue());
//            //修改后的request
//            ServerHttpRequest modifiedRequest = exchange.getRequest()
//                .mutate()
//                .build();
//            //将修改后的request放入exchange
//            ServerWebExchange modifiedExchange = exchange.mutate()
//                .request(modifiedRequest)
//                .build();
//			//传给下一个过滤器
//            return chain.filter(modifiedExchange);
//        });
    }
}
